﻿namespace TestWIP
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    using System.Xml.XPath;

    using com.crownpack;
    using com.crownpack.Extensions.FileStreamExtensions;
    using com.crownpack.Extensions.SharePointExtensions;
    using com.crownpack.InitiativesDao;

    using Microsoft.SharePoint;

    public static class SPViewExtensions
    {
        #region Methods

        public static void SetSchemaXml( this SPView view, string schema )
        {
            XDocument schemaXml = XDocument.Parse( schema );
            MethodInfo setInnerXmlForNode = typeof( SPView ).GetMethod( "SetInnerXmlForNode", BindingFlags.Instance | BindingFlags.NonPublic );

            if ( setInnerXmlForNode == null )
            {
                view.SetViewXml( schema );
            }
            else
            {
                foreach ( XElement child in schemaXml.Root.Elements( ) )
                {
                    setInnerXmlForNode.Invoke( view, new object[ ] { child.Name.LocalName, child.GetContent( ) } );
                }
            }
        }

        private static string GetContent( this XElement element )
        {
            return element.DescendantNodes( ).Aggregate(
                new StringBuilder( ),
                ( sb, node ) => sb.Append( node.ToString( SaveOptions.DisableFormatting ) ),
                sb => sb.ToString( )
            );
        }

        #endregion Methods
    }

    class Class2
    {
        #region Fields

        string aa = "<View><ViewFields><FieldRef Name='Attachments' /><FieldRef Name='cpInitNo' /><FieldRef Name='cpPrdCat' /><FieldRef Name='cpInitDscr' /><FieldRef Name='cpLocationName' /><FieldRef Name='cpSalesrepName' /><FieldRef Name='cpPC' /><FieldRef Name='cpRealDt' /><FieldRef Name='cpEstTotSavTot' /><FieldRef Name='cpCustInitNo' /></ViewFields><Query><GroupBy Collapse='TRUE' GroupLimit='300'><FieldRef Name='cpPrdCat' /></GroupBy><OrderBy><FieldRef Name='Created' Ascending='FALSE' /></OrderBy></Query><Aggregations Value='On'><FieldRef Name='cpEstTotSavTot' Type='SUM' /></Aggregations></View>";
        List<string> _BaseFields;

        #endregion Fields

        #region Properties

        List<string> BaseFields
        {
            get
            {
                if ( _BaseFields == null )
                {
                    _BaseFields = new List<string>( );
                    _BaseFields.AddRange( new string[ ] {
                        "Title",
                    }.ToList( ) );
                }
                return _BaseFields;
            }
            set
            {
                _BaseFields = value;
            }
        }

        #endregion Properties

        #region Methods

        public void a( )
        {
            string r = "http://win-pv542842fga:8888/sites/cp/wip/i2e";
            string s = "http://win-pv542842fga:8888/sites/cp/eaton/i2e";
            string list = "test";
            using ( SPSite spSite = new SPSite( s ) )
            {
                using ( SPWeb spWeb = spSite.OpenWeb( ) )
                {
                    //string parentweburl = spWeb.ParentWeb.Url;

                    //InitiativesConfigurationDao dao = new InitiativesConfigurationDao( r);
                    //var xx = dao.GetByClientSite( "http://win-pv542842fga:8888/sites/cp/eaton" );

                    //string assembly = Assembly.GetAssembly( typeof( InitiativesItemEventReceiver ) ).FullName;
                    //string className = typeof( InitiativesItemEventReceiver ).FullName;

                    SPList spList = spWeb.Lists[ "initiatives" ];

                    //List<SPEventReceiverDefinition> l = new List<SPEventReceiverDefinition>( );
                    //foreach ( SPEventReceiverDefinition v in spList.EventReceivers )
                    //    if ( ( v.Type == SPEventReceiverType.ItemAdded ||
                    //        v.Type == SPEventReceiverType.ItemUpdated ) &&
                    //        v.Assembly.Equals( assembly ) && v.Class.Equals( className ) )
                    //        l.Add( v );
                    //for ( int i = l.Count - 1; i >= 0; i-- )
                    //    l[ i ].Delete( );

                    //spList.EventReceivers.Add( SPEventReceiverType.ItemAdded, assembly, className );
                    //spList.EventReceivers.Add( SPEventReceiverType.ItemUpdated, assembly, className );
                    //return;
                    //List<SPField> fields = spList.Fields.Cast<SPField>( ).ToList( );
                    //string internalName = string.Empty;
                    //foreach ( SPField field in fields )
                    //{
                    //    if ( field.FieldTypeDefinition.TypeName.Equals( "Customer", StringComparison.OrdinalIgnoreCase ) )
                    //    {
                    //        internalName = field.InternalName;
                    //        break;
                    //    }
                    //}

                    foreach ( SPListItem spListItem in spList.Items )
                    {
                        bool update = false;
                        CustomerFieldValue v = new CustomerFieldValue( spListItem[ "cpLocation" ], spWeb.Url );
                        if ( v == null )
                            continue;

                        Customer o = v.UnderlyingObject;
                        if ( o == null )
                            continue;

                        if ( spListItem.ContainsField( Layout.Address1 ) )
                        {
                            spListItem[ Layout.Address1 ] = o.Address1;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.Branch ) )
                        {
                            spListItem[ Layout.Branch ] = o.Branch;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.BranchManager ) )
                        {
                            spListItem[ Layout.BranchManager ] = o.BranchManager;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.BranchName ) )
                        {
                            spListItem[ Layout.BranchName ] = o.BranchName;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.City ) )
                        {
                            spListItem[ Layout.City ] = o.City;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.DivisionCode ) )
                        {
                            spListItem[ Layout.DivisionCode ] = o.DivisionCode;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.GroupCode ) )
                        {
                            spListItem[ Layout.GroupCode ] = o.GroupCode;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.LocationName ) )
                        {
                            spListItem[ Layout.LocationName ] = o.LocationName;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.LocationNo ) )
                        {
                            spListItem[ Layout.LocationNo ] = o.LocationNo;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.ManagerEMail ) )
                        {
                            spListItem[ Layout.ManagerEMail ] = o.ManagerEMail;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.NA_ManagerEmailAddress ) )
                        {
                            spListItem[ Layout.NA_ManagerEmailAddress ] = o.NA_ManagerEmailAddress;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.NA_ManagerName ) )
                        {
                            spListItem[ Layout.NA_ManagerName ] = o.NA_ManagerName;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.NA_ManagerNo ) )
                        {
                            spListItem[ Layout.NA_ManagerNo ] = o.NA_ManagerNo;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.NA_ManagerPhone ) )
                        {
                            spListItem[ Layout.NA_ManagerPhone ] = o.NA_ManagerPhone;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.ParentCustomerName ) )
                        {
                            spListItem[ Layout.ParentCustomerName ] = o.ParentCustomerName;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.ParentCustomerNo ) )
                        {
                            spListItem[ Layout.ParentCustomerNo ] = o.ParentCustomerNo;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.Salesrep ) )
                        {
                            spListItem[ Layout.Salesrep ] = o.Salesrep;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.SalesrepEmailAddress ) )
                        {
                            spListItem[ Layout.SalesrepEmailAddress ] = o.SalesrepEmailAddress;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.SalesrepName ) )
                        {
                            spListItem[ Layout.SalesrepName ] = o.SalesrepName;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.SalesrepPhone ) )
                        {
                            spListItem[ Layout.SalesrepPhone ] = o.SalesrepPhone;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.SectorCode ) )
                        {
                            spListItem[ Layout.SectorCode ] = o.SectorCode;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.St ) )
                        {
                            spListItem[ Layout.St ] = o.St;
                            update = true;
                        }
                        if ( spListItem.ContainsField( Layout.Zip ) )
                        {
                            spListItem[ Layout.Zip ] = o.Zip;
                            update = true;
                        }

                        if ( update )
                            spListItem.UpdateOverwriteVersion( );
                    }
                }
            }
        }

        public void AA( )
        {
            string r = "http://win-pv542842fga:8888/sites/cp";
            string s = "http://win-pv542842fga:8888/sites/cp";
            string list = "test";
            using ( SPSite spSite = new SPSite( s ) )
            {
                using ( SPWeb spWeb = spSite.OpenWeb( ) )
                {
                    SPContentType parentContentType = spWeb.GetContentTypeByName( "Item" );
                    List<SPField> fields = new List<SPField>( );
                    SPField field = spWeb.GetFieldByStaticName( "cpConfigActive" );
                    fields.Add( field );
                    SPContentType spContentType = spWeb.CreateContentType( parentContentType, "ABC", "ABC1_Test", "This is the description", true, fields.ToArray( ) );
                    SPFieldLink link = spContentType.FieldLinks[ "Title" ];
                    link.DisplayName = "test";
                    link = spContentType.FieldLinks[ "LinkTitle" ];
                    link.DisplayName = "test";
                    link = spContentType.FieldLinks[ "LinkTitleNoMenu" ];
                    link.DisplayName = "test";

                    ////spContentType.Fields[ "Title" ].Title = "Test";
                    ////spContentType.Fields[ "LinkTitle" ].Title = "Test";
                    ////spContentType.Fields[ "LinkTitleNoMenu" ].Title = "Test";
                    spContentType.Update( );
                }
            }
        }

        public void b( string fileName )
        {
            string s = "http://win-pv542842fga:8888/sites/cp/wip/i2e";
            using ( SPSite spSite = new SPSite( s ) )
            {
                using ( SPWeb spWeb = spSite.OpenWeb( ) )
                {
                    SPList spList = spWeb.Lists.GetListByRootFolder( "initiativeseaton" );
                    FileInfo fi = new FileInfo( fileName );
                    if ( fi.Exists )
                        fi.Delete( );
                    FileStream fs = fi.OpenWrite( );
                    foreach ( SPField spField in spList.Fields )
                    {
                        //if ( spField.CanBeDeleted || BaseFields.Contains( spField.InternalName ) )
                        fs.WriteLine( "{0}\t{1}\t{2}", spField.InternalName, spField.FieldTypeDefinition.TypeDisplayName, spField.Title );
                    }
                    fs.SafeClose( );
                }
            }
        }

        public void c( )
        {
            string r = "http://win-pv542842fga:8888/sites/cp/wip/i2e";
            string s = "http://win-pv542842fga:8888/sites/cp/eaton/i2e";
            string list = "test";
            using ( SPSite spSite = new SPSite( s ) )
            {
                using ( SPWeb spWeb = spSite.OpenWeb( ) )
                {
                    SPList spList = spWeb.Lists.GetListByRootFolder( "initiatives" );

                    SPView view = spList.CreateView( "d", "Test", 100, true, true, SPViewCollection.SPViewType.Html, true );
                    view.SetQueryXml( aa );
                    view.SetAggregationsXml( aa );
                    view.SetViewFieldXml( aa );
                    view.Update( );
                    return;
                    view.Aggregations = "";
                    view.Toolbar = "Standard";
                    view.TabularView = false;
                    string xml = view.SchemaXml;//                    view.GetViewXml( );
                    XmlDocument targetDocument = new XmlDocument( );
                    targetDocument.LoadXml( xml );
                    XmlElement targetElement = targetDocument.DocumentElement;
                    XmlDocument sourceDocument = new XmlDocument( );
                    sourceDocument.LoadXml( aa );
                    XmlElement sourceElement = sourceDocument.DocumentElement;
                    setXmlNode( sourceElement, targetElement, "ViewFieldsx" );
                    setXmlNode( sourceElement, targetElement, "Query" );
                    setXmlNode( sourceElement, targetElement, "Aggregations" );
                    ////XmlNode sourceViewFields = sourceRoot.SelectSingleNode( "ViewFields" );
                    ////viewFields.InnerXml = sourceViewFields.InnerXml;
                    ////XmlNode targetQuery = targetRoot.SelectSingleNode( "Query" );
                    ////XmlNode sourceQuery = sourceRoot.SelectSingleNode( "Query" );
                    ////targetQuery.InnerXml = sourceQuery.InnerXml;
                    //spList.Views.Delete( view.ID );
                    //SPView newview=new SPView(spList,targetDocument);
                    //newview.Update( );
                    ///spList.Update( );
                    //view.SetViewXml}
                    view.SetSchemaXml( targetDocument.OuterXml );
                    view.Update( );
                }
            }
        }

        void setXmlNode( XmlElement sourceElement, XmlElement targetElement, string xpath )
        {
            XmlNode sourceNode = sourceElement.SelectSingleNode( xpath );
            XmlNode targetNode = targetElement.SelectSingleNode( xpath );
            targetNode.InnerXml = sourceNode.InnerXml;
            foreach ( XmlAttribute attribute in sourceNode.Attributes )
            {
                targetNode.Attributes.RemoveNamedItem( attribute.Name );
                XmlAttribute attrib = targetElement.OwnerDocument.CreateAttribute( attribute.Name );
                attrib.Value = attribute.Value;
                targetNode.Attributes.Append( attrib );
            }
        }

        #endregion Methods
    }
}